package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Session.GetUserAccountsReq;
import net.ib.mntalk.protocol.Session.GetUserAccountsRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.util.MTalkLogWriter;
import net.ib.mtalk.util.NotifyingAsyncQueryHandler;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class GetUserAccountsTask extends AsyncNetTask {
	
	private Context mContext;
	private Handler mUiHandler;
	private NotifyingAsyncQueryHandler mDbHandler;
	private int index;
	private GetUserAccountsReq mGetUserAccountsReq = new GetUserAccountsReq();
	public GetUserAccountsTask(Context _context, Handler _uiHandler, GetUserAccountsReq getUserAccountsReq) {
		super(_context, _uiHandler);
		mContext = _context;
		mUiHandler = _uiHandler;
		//index = _index;
		mGetUserAccountsReq = getUserAccountsReq;
	}

	@Override
	protected TcpEnvelope onPreExecute() {
		/*GetUserAccountsReq getUserAccountsReq = new GetUserAccountsReq();
		
		UUIDSlicePredicate slicePredicate = new UUIDSlicePredicate();
		slicePredicate.setId(index, GpbSupport.makeUuidMsg(333, 444));
		UUIDSliceRange range = new UUIDSliceRange();
		range.setAscending(true);
		range.setMaxCount(0);	// TODO 전부다받아오기
		slicePredicate.setSliceRange(range);
		
		getUserAccountsReq.setPredicate(slicePredicate);*/

		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(mGetUserAccountsReq)
			.setMethodId(Session.User.GetUserAccounts)
			.build();
		return rev;
	}

	@Override
	protected void onPostExecute(int resultCode, Object requestObj,
			Object resultObj) {
		MTalkLogWriter.d("GetUserAccountsTask.onPostExecute() resultCode : " + resultCode);
		if (resultObj == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) resultObj;
		GetUserAccountsRes getUserAccountsRes = (GetUserAccountsRes) resultEnvelope.getMessage();
		
		MTalkLogWriter.d("GetUserAccountsTask ResponseCode : " + getUserAccountsRes.getResponseCode());
		
		if(getUserAccountsRes.getResponseCode() == Common.SUCCESS){
			Message msg = mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_GET_USER_ACCOUNT_SUCCESS);
			msg.obj = getUserAccountsRes;
			mUiHandler.sendMessageAtFrontOfQueue(msg);
			
		} else {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_GET_USER_ACCOUNT_FAIL));
		}
	}

}
